// -*- coding: utf-8 -*-
#include "syncdialog.h"
#include "ui_syncdialog.h"
#include <QFileInfo>
#include <QScrollBar>

SyncDialog::SyncDialog(const QString &leftFilePath, const QString &rightFilePath, QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::SyncDialog)
    , m_leftFilePath(leftFilePath)
    , m_rightFilePath(rightFilePath)
    , m_isModified(false)
{
    ui->setupUi(this);
    
    setWindowTitle(QString("文件比较: %1 vs %2").arg(QFileInfo(m_leftFilePath).fileName()).arg(QFileInfo(m_rightFilePath).fileName()));
    
    // 创建高亮器
    m_leftHighlighter = new DiffHighlighter(ui->leftTextEdit->document());
    m_rightHighlighter = new DiffHighlighter(ui->rightTextEdit->document());
    m_fileComparator = new FileComparator(this);
    
    // 连接非文本修改相关的信号和槽
    connect(ui->leftToRightButton, &QPushButton::clicked, this, &SyncDialog::on_leftToRightButton_clicked);
    connect(ui->rightToLeftButton, &QPushButton::clicked, this, &SyncDialog::on_rightToLeftButton_clicked);
    connect(ui->saveButton, &QPushButton::clicked, this, &SyncDialog::on_saveButton_clicked);
    
    // 先加载文件内容和更新差异高亮
    loadFileContents();
    updateDiffHighlight();
    
    // 初始化完成后再连接textChanged信号，避免加载文件内容时触发修改标记
    connect(ui->leftTextEdit, &QTextEdit::textChanged, this, &SyncDialog::on_textChanged);
    connect(ui->rightTextEdit, &QTextEdit::textChanged, this, &SyncDialog::on_textChanged);
    
    // 添加左右文本编辑框的垂直滚动条同步滚动功能
    connect(ui->leftTextEdit->verticalScrollBar(), &QScrollBar::valueChanged, this, [=](int value) {
        if (ui->rightTextEdit->verticalScrollBar()->value() != value) {
            ui->rightTextEdit->verticalScrollBar()->blockSignals(true);
            ui->rightTextEdit->verticalScrollBar()->setValue(value);
            ui->rightTextEdit->viewport()->update();
            ui->rightTextEdit->verticalScrollBar()->blockSignals(false);
        }
    });
    
    connect(ui->rightTextEdit->verticalScrollBar(), &QScrollBar::valueChanged, this, [=](int value) {
        if (ui->leftTextEdit->verticalScrollBar()->value() != value) {
            ui->leftTextEdit->verticalScrollBar()->blockSignals(true);
            ui->leftTextEdit->verticalScrollBar()->setValue(value);
            ui->leftTextEdit->viewport()->update();
            ui->leftTextEdit->verticalScrollBar()->blockSignals(false);
        }
    });
}

SyncDialog::~SyncDialog()
{
    // 断开所有信号连接，避免在析构过程中触发回调
    disconnect(ui->leftTextEdit, &QTextEdit::textChanged, this, &SyncDialog::on_textChanged);
    disconnect(ui->rightTextEdit, &QTextEdit::textChanged, this, &SyncDialog::on_textChanged);
    disconnect(ui->leftTextEdit->verticalScrollBar(), &QScrollBar::valueChanged, nullptr, nullptr);
    disconnect(ui->rightTextEdit->verticalScrollBar(), &QScrollBar::valueChanged, nullptr, nullptr);
    
    // 设置高亮器的document为nullptr，避免在销毁时触发事件
    m_leftHighlighter->setDocument(nullptr);
    m_rightHighlighter->setDocument(nullptr);
    
    // 按照正确的顺序销毁对象
    delete m_leftHighlighter;
    delete m_rightHighlighter;
    delete m_fileComparator;
    delete ui;
}

void SyncDialog::closeEvent(QCloseEvent *event)
{
    if (m_isModified) {
        QMessageBox::StandardButton reply;
        reply = QMessageBox::question(this, "保存提示", "文件已修改，是否保存？",
                                      QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
        
        if (reply == QMessageBox::Cancel) {
            event->ignore();
            return;
        } else if (reply == QMessageBox::Save) {
            on_saveButton_clicked();
        }
    }
    event->accept();
}

void SyncDialog::keyPressEvent(QKeyEvent *event)
{
    if (event->modifiers() == Qt::ControlModifier && event->key() == Qt::Key_S) {
        on_saveButton_clicked();
    } else {
        QDialog::keyPressEvent(event);
    }
}

void SyncDialog::on_leftToRightButton_clicked()
{
    ui->rightTextEdit->setPlainText(ui->leftTextEdit->toPlainText());
    markAsModified();
    updateDiffHighlight();
}

void SyncDialog::on_rightToLeftButton_clicked()
{
    ui->leftTextEdit->setPlainText(ui->rightTextEdit->toPlainText());
    markAsModified();
    updateDiffHighlight();
}

void SyncDialog::on_saveButton_clicked()
{
    saveFile(m_leftFilePath, ui->leftTextEdit->toPlainText());
    saveFile(m_rightFilePath, ui->rightTextEdit->toPlainText());
    m_isModified = false;
    QMessageBox::information(this, "保存成功", "文件已成功保存");
}

void SyncDialog::on_textChanged()
{
    markAsModified();
    updateDiffHighlight();
}

void SyncDialog::loadFileContents()
{
    QFile leftFile(m_leftFilePath);
    QFile rightFile(m_rightFilePath);
    
    if (leftFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream leftStream(&leftFile);
        ui->leftTextEdit->setPlainText(leftStream.readAll());
        leftFile.close();
    }
    
    if (rightFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream rightStream(&rightFile);
        ui->rightTextEdit->setPlainText(rightStream.readAll());
        rightFile.close();
    }
}

void SyncDialog::saveFile(const QString &filePath, const QString &content)
{
    QFile file(filePath);
    if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QTextStream stream(&file);
        stream << content;
        file.close();
    } else {
        QMessageBox::warning(this, "保存失败", QString("无法保存文件: %1").arg(filePath));
    }
}

void SyncDialog::updateDiffHighlight()
{
    // 暂时断开textChanged信号连接，防止递归调用
    disconnect(ui->leftTextEdit, &QTextEdit::textChanged, this, &SyncDialog::on_textChanged);
    disconnect(ui->rightTextEdit, &QTextEdit::textChanged, this, &SyncDialog::on_textChanged);
    
    QString leftContent = ui->leftTextEdit->toPlainText();
    QString rightContent = ui->rightTextEdit->toPlainText();
    
    QStringList leftLines = leftContent.split("\n");
    QStringList rightLines = rightContent.split("\n");
    
    QList<int> differentLines;
    int maxLines = qMax(leftLines.size(), rightLines.size());
    
    for (int i = 0; i < maxLines; i++) {
        QString leftLine = (i < leftLines.size()) ? leftLines[i] : "";
        QString rightLine = (i < rightLines.size()) ? rightLines[i] : "";
        
        if (leftLine != rightLine) {
            differentLines.append(i);
        }
    }
    
    m_leftHighlighter->setHighlightLines(differentLines);
    m_rightHighlighter->setHighlightLines(differentLines);
    
    // 重新连接textChanged信号
    connect(ui->leftTextEdit, &QTextEdit::textChanged, this, &SyncDialog::on_textChanged);
    connect(ui->rightTextEdit, &QTextEdit::textChanged, this, &SyncDialog::on_textChanged);
}

void SyncDialog::markAsModified()
{
    m_isModified = true;
    setWindowTitle(QString("文件比较: %1 vs %2 [已修改]")
                   .arg(QFileInfo(m_leftFilePath).fileName())
                   .arg(QFileInfo(m_rightFilePath).fileName()));
}